// pages/activityDetail/activityDetail.js
// import {} from "../../services/activityDetailReq";

import {
    activityBuyActivity
} from '../../services/activityDetailReq';
import {
    getItem
} from '../../utils/storge';

const {
    getMessage,
    joinActivity,
    addMsg,
    jobListByActivityId,
    activityGetOne,
} = require('../../services/activityDetailReq');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        activityObj: {},
        message: [],
        pageNum: 1,
        pageSize: 10,
        jobId: 0,
        jobShow: false,
        jobList: [],
        showComment: false,
        commentVaule: '',
        joinActivityParams: {
            activityId: null,
            jobId: null,
        },
        obj: {},
        userId: null,
        familyInfo: [],
        MemberId: null,
        show: false,
        targetActivityId: null,
    },

    /**
     *
     * @param {string} target
     * @param {any} value
     * @return {?object}
     * */
    implementModify(target, value) {
        let targetObj = this.data[target];
        if (targetObj === value) return null;
        return this.setData({
            [target]: value,
        });
    },

    trigger(target) {
        let targetObj = this.data[target];
        targetObj = !targetObj;
        this.setData({
            [target]: targetObj,
        });
    },
    onLoad: function (options) {
        let volunteerInfo = getItem() ?? [];
        let familyInfo = getItem('familyInfo')?.member ?? [];

        const {
            volunteerId: MemberId
        } = volunteerInfo;

        const {
            id: activityId
        } = options;
        if (!familyInfo) familyInfo = [volunteerInfo];
        this.implementModify('joinActivityParams.activityId', activityId);
        this.implementModify('familyInfo', familyInfo);
        this.implementModify('MemberId', MemberId);


        activityGetOne({
            activityId,
        }, res => {
            let activityObj = res.data.data;
            try {
                activityObj.activity.activityAddress = JSON.parse(activityObj.activity.activityAddress);
            } catch (e) {}
            console.log(activityObj)
            this.implementModify('activityObj', activityObj);
        });
        // 获取留言
        getMessage(activityId, this.data.pageNum, this.data.pageSize, res => {
            this.implementModify('message', this.data.message.concat(res.data.data.list));
        });

        //     获取岗位信息
        jobListByActivityId(
            activityId,
            res => {
                const {
                    data: jobList
                } = res.data;

                this.implementModify('jobList', jobList);
            },
        );

    },


    // 写留言
    handleWriteMessage() {

        const volunteerId = getItem()?.volunteerId;
        if (!volunteerId) return wx.showToast({
            title: '请先登陆',
            icon: 'error',
            duration: 2000,
            success(res) {
                setTimeout(() => wx.navigateTo({
                    url: '../login/login',
                }), 2000);
            },
        });
        this.implementModify('showComment', true);

    },

    handleComment(e) {
        wx.showLoading({
            title: '留言中',
            mask: true,
        });

        const activityId = this.data.activityObj.activity.activityId;
        const messageContent = this.data.commentVaule;

        if (!messageContent) {
            return wx.showToast({
                title: '留言不许为空',
                icon: 'error',
                mask: true,
            });
        }

        const volunteerInfo = getItem() ?? {};
        const {
            volunteerAvatar,
            volunteerId,
            volunteerName,
        } = volunteerInfo;

        let obj = {
            activityId,
            messageContent,
            volunteerAvatar,
            volunteerId,
            volunteerName,
        };

        addMsg(obj, res => {
            if (res.data.code !== 0) {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                });
            } else {
                wx.showToast({
                    title: '留言成功',
                });
                getMessage(
                    obj.activityId,
                    this.data.pageNum,
                    this.data.pageSize,
                    res => {
                        console.log(res.data.data.list);
                        this.setData({
                            message: res.data.data.list,
                        });
                    });
                this.setData({
                    showComment: false,
                    commentVaule: '',
                });
            }
        });
    },
    handleCommentChange(e) {
        const {
            value: commentVaule
        } = e.detail;
        this.implementModify('commentVaule', commentVaule);
    },
    handleCommentClose() {
        this.implementModify('commentVaule', '');
        this.trigger('showComment', false);
    },

    handleGoMap(e) {
        let position = e.currentTarget.dataset.position;
        wx.openLocation({
            latitude: position.lat, //维度
            longitude: position.lng, //经度
            name: '目的地', //目的地定位名称
            scale: 15, //缩放比例
            address: position.address, //导航详细地址
        });
    },

    handleJoinActivity() {
        if (!getItem()) {
            wx.showToast({
                title: '请先登陆',
                icon: 'error',
            });
            return wx.navigateTo({
                url: '../login/login',
            });
        }

        let params = this.data.joinActivityParams;
        params['volunteerId'] = this.data.MemberId;

        
        for (let param in params) {
            if (!params[param]) return wx.showToast({
                title: '请选择岗位',
                icon: 'error',
            });
        }

        wx.Loading({
            title: '加载中...',
        });
        const isFree = this.data.activityObj?.activity?.activityIsfree;
        if (!isFree) {
            return activityBuyActivity({
                    volunterId: params['volunteerId'],
                    activityId: params['activityId'],
                    jobId: params['jobId'],
                },
                res => {
                    wx.Loading({
                        title: '下单中',
                    });
                    if (res.data.data.code !== 0) {
                        wx.showToast({
                            title: res.data.data.msg,
                            icon: 'error',
                        });
                    } else {
                        let req = res.data.data;

                        if (req.data.code) {
                            return wx.showToast({
                                title: '出错啦',
                                icon: 'error',
                            });
                        }
                        req.data['package'] = 'prepay_id=' + req.data['package'];
                        // console.log( req.data["package"])
                        wx.requestPayment({
                            ...req.data,
                            paySign: req.data.sign,
                            success(res) {
                                wx.hideLoading();
                                return wx.showToast({
                                    title: '支付成功',
                                });
                            },
                            fail(res) {
                                wx.hideLoading();
                                return wx.showToast({
                                    title: '你已经取消支付',
                                    icon: 'error',
                                });

                            },

                        });
                    }
                },
            );
        }

        return joinActivity(params, res => {

            if (res.data.code !== 0) {
                return wx.showToast({
                    title: res.data.msg,
                    icon: 'error',
                });
            }

            return wx.showToast({
                title: '报名成功',
                icon: 'error',
            });
        });
    },
    handleConfirmJob(e) {
        if (e.detail !== 'right') return null;
        let joinActivityParams = this.data.joinActivityParams;
        joinActivityParams['jobId'] = e.currentTarget.dataset.id;
        this.setData({
            joinActivityParams,
        });
        wx.showToast({
            title: '当前选择了' + e.currentTarget.dataset.name,
        });
    },

    onClose() {
        this.trigger('show');
    },
    handleSelectMember(event) {
        const {
            id: MemberId
        } = event.currentTarget.dataset;
        this.implementModify('MemberId', MemberId);

    },
    handleToSignInShow() {
        const volunteerId = wx.getStorageSync('volunteerInfo').volunteerId;
        if (!volunteerId) return wx.showToast({
            title: '请先登陆',
            icon: 'error',
            duration: 2000,
            mask: true,
            success(res) {
                setTimeout(() => wx.navigateTo({
                    url: '../login/login',
                }), 2000);
            },
        });
        this.onClose();
    },


});